package com.lcxw.hxzbadmin.controller.giftandcubecontroller;

import com.lcxw.hxzbadmin.entity.requestbean.GiftIconUpload;
import com.lcxw.hxzbcommon.entity.ErrorCode;
import java.util.LinkedHashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.obs.services.ObsClient;
import com.obs.services.model.HttpMethodEnum;
import com.obs.services.model.PutObjectResult;
import com.obs.services.model.TemporarySignatureRequest;
import com.obs.services.model.TemporarySignatureResponse;
import java.io.ByteArrayInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;
import com.lcxw.hxzbapi.entity.response.Response;
import com.lcxw.hxzbcommon.common.ObsUtil;
import com.lcxw.hxzbcommon.common.StringUtil;
import com.lcxw.hxzbcommon.entity.CommonBean;

@RestController
@CrossOrigin
@RequestMapping("admin/gift/img")
public class GiftUrlController {

    private Logger logger = LoggerFactory.getLogger(GiftUrlController.class);

    private static ObsClient obsClient = new ObsUtil()
        .getObsClient();

    @PostMapping("/upload/icon")
    public Response uploadGiftImg(@RequestBody @Validated GiftIconUpload requestParams) {

        String giftName = requestParams.getGiftName();
        String picName = requestParams.getPicName();
        String suffix = picName.substring(picName.lastIndexOf("."));
        String imgOrigin = requestParams.getImg();
        String imgName = "gift/icon/" + giftName + "_icon." + suffix;

        return upload(imgOrigin, imgName);
    }


    @PostMapping("/upload/bigIcon")
    public Response uploadGiftBigIcon(@RequestBody @Validated GiftIconUpload requestParams) {

        String giftName = requestParams.getGiftName();
        String picName = requestParams.getPicName();
        String suffix = picName.substring(picName.lastIndexOf("."));
        String imgName = "gift/bigIcon/" + giftName + "_bigIcon." + suffix;
        String imgOrigin = requestParams.getImg();

        return upload(imgOrigin, imgName);
    }

    @PostMapping("/upload/flash")
    public Response uploadGiftFlash(@RequestBody @Validated GiftIconUpload requestParams) {
        String giftName = requestParams.getGiftName();
        String picName = requestParams.getPicName();
        String suffix = picName.substring(picName.lastIndexOf("."));
        String imgOrigin = requestParams.getImg();
        String imgName = "gift/flash/" + giftName + "_flash." + suffix;
        return upload(imgOrigin, imgName);
    }


    private Response upload(String imgOrigin, String imgName) {
        byte[] imgBytes;
        try {
            //拿到前台传过来的img图片的原始数据
            //对原始数据解码，获得字节数组
            imgBytes = new BASE64Decoder().decodeBuffer(imgOrigin);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("decrypt failed");
            return Response
                .common(logger, "decrypt failed", ErrorCode.INTERNAL_ERROR, "internal failed",
                    null);
        }

        PutObjectResult putObjectResult = obsClient
            .putObject("ywpd-picture", imgName, new ByteArrayInputStream(imgBytes));

        //判断是否上传到华为OBS失败
        if (null == putObjectResult) {
            logger.error("put img to obs failed");
            return Response
                .common(logger, "put img to obs failed", ErrorCode.EXTERNAL_ERROR, "internal error",
                    null);
        }

        //上传成功后，需要获取该图片的下载url
        //生成头像url的过期时间，设置为3年
        long expireSeconds = CommonBean.IMGEXPIREDTIME;

        //下面是生成头像URL的方法
        TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET,
            expireSeconds);
        request.setBucketName("ywpd-picture");
        request.setObjectKey(imgName);
        TemporarySignatureResponse temporarySignatureResponse = obsClient
            .createTemporarySignature(request);
        String imgUrl = temporarySignatureResponse.getSignedUrl();

        Map<String, Object> data = new LinkedHashMap<>();
        data.put("imgUrl", imgUrl);

        return Response.common(logger, "upload gift img success.", 0, "success", data);
    }


}
